package com.legsem.legstar;

import java.beans.PropertyChangeListener;
import java.beans.PropertyChangeSupport;

/**
 * Common code for bound beans.
 * 
 */
public abstract class LegStarBoundBean {

    protected transient PropertyChangeSupport propertyChange;

    /**
     * Support for bound properties.
     * 
     * @return the property change support
     */
    public PropertyChangeSupport getPropertyChange() {
        if (propertyChange == null) {
            propertyChange = new PropertyChangeSupport(this);
        }
        return propertyChange;
    }

    /**
     * Fire a property change for listeners.
     * 
     * @param propertyName the property that was changed
     * @param oldValue previous value
     * @param newValue new value
     */
    public void firePropertyChange(String propertyName, Object oldValue,
            Object newValue) {
        getPropertyChange()
                .firePropertyChange(propertyName, oldValue, newValue);

    }

    /**
     * Add a listener for all changes.
     * 
     * @param listener the listener to add
     */
    public synchronized void addPropertyChangeListener(
            PropertyChangeListener listener) {

        getPropertyChange().addPropertyChangeListener(listener);
    }

    /**
     * Add a listener for changes on a given property.
     * 
     * @param propertyName the property name to watch
     * @param listener the listener to add
     */
    public synchronized void addPropertyChangeListener(String propertyName,
            PropertyChangeListener listener) {

        getPropertyChange().addPropertyChangeListener(propertyName, listener);
    }

    /**
     * Whether a property has a listener monitoring its changes.
     * 
     * @param propertyName the property name
     * @return true if there is at least one listener for this property
     */
    public synchronized boolean hasListeners(String propertyName) {

        return getPropertyChange().hasListeners(propertyName);
    }

    /**
     * Remove a global change listener.
     * 
     * @param listener the listener to remove
     */
    public synchronized void removePropertyChangeListener(
            PropertyChangeListener listener) {

        getPropertyChange().removePropertyChangeListener(listener);
    }

    /**
     * Remove a listener on a given property.
     * 
     * @param propertyName the property to remove listener from
     * @param listener the listener to remove
     */
    public synchronized void removePropertyChangeListener(String propertyName,
            PropertyChangeListener listener) {

        getPropertyChange()
                .removePropertyChangeListener(propertyName, listener);
    }
}
